package com.zdxf.util;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.sql.Timestamp;

/**
 * @author Administrator
 */
public class Json {
    final static String _DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static void toJson(Result result, HttpServletResponse response) throws Exception {
        response.setContentType("text/json");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");

//        WebConfig webConfig = new WebConfig();

        PrintWriter writer = response.getWriter();

        // 如果时间类型值为null，则返回空串
        ValueFilter dateFilter = (Object var1, String var2, Object var3) -> {
            try {
                if (var3 == null && var1 != null && Timestamp.class.isAssignableFrom(var1.getClass().getDeclaredField(var2).getType())) {
                    return "";
                }

                if (var3 == null && var1 != null && Double.class.isAssignableFrom(var1.getClass().getDeclaredField(var2).getType())) {
                    return "";
                }
            } catch (Exception e) {
            }
            return var3;
        };

        String json = JSONObject.toJSONString(result,
                dateFilter,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteMapNullValue,
//                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullBooleanAsFalse,
//                SerializerFeature.WriteDateUseDateFormat,
                SerializerFeature.PrettyFormat
                // 避免循环引用
//                SerializerFeature.DisableCircularReferenceDetect
        );
        writer.write(json);
        writer.close();
    }
}
